package com.pai4j.ugc.controller;

import com.pai4j.common.bean.PAIPageResponseBeanUtil;
import com.pai4j.common.bean.PAIResponseBean;
import com.pai4j.common.bean.PAIResponseBeanUtil;
import com.pai4j.domain.vo.request.community.CreateCommunityContributionRequestVO;
import com.pai4j.domain.vo.request.community.UpdateCommunityContributionRequestVO;
import com.pai4j.domain.vo.request.community.ContributionStatusChangeRequestVO;
import com.pai4j.domain.vo.response.community.CommunityContributionBaseResponseVO;
import com.pai4j.domain.vo.response.community.CommunityContributionDetailResponseVO;
import com.pai4j.remote.ugc.CommunityContributionClient;
import com.pai4j.ugc.service.community.CommunityContributionService;
import com.pai4j.ugc.service.community.CommunityContributionWorkflowService;
import com.pai4j.ugc.service.community.CommunityContributionStatisticsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 社区共建控制器
 *
 * @author: CYM-pai
 * @date: 2025/07/30 12:00
 **/
@Slf4j
@RestController
public class CommunityContributionController implements CommunityContributionClient {

    @Autowired
    private CommunityContributionService contributionService;
    @Autowired
    private CommunityContributionWorkflowService workflowService;
    @Autowired
    private CommunityContributionStatisticsService statisticsService;

    /**
     * 创建社区共建
     *
     * @param createRequest 创建请求
     * @return 共建ID
     */
    @Override
    public PAIResponseBean<Long> create(@RequestBody CreateCommunityContributionRequestVO createRequest) {
        return PAIResponseBeanUtil.success(contributionService.create(createRequest));
    }

    /**
     * 更新社区共建
     *
     * @param updateRequest 更新请求
     * @return 更新结果
     */
    @Override
    public PAIResponseBean<Boolean> update(@RequestBody UpdateCommunityContributionRequestVO updateRequest) {
        return PAIResponseBeanUtil.success(contributionService.update(updateRequest));
    }

    /**
     * 删除社区共建
     *
     * @param contributionId 共建ID
     * @param operator       操作人
     * @return 删除结果
     */
    @Override
    public PAIResponseBean<Boolean> delete(@PathVariable Long contributionId, @RequestParam String operator) {
        return PAIResponseBeanUtil.success(contributionService.delete(contributionId, operator));
    }

    /**
     * 获取共建详情
     *
     * @param contributionId 共建ID
     * @return 共建详情
     */
    @Override
    public PAIResponseBean<CommunityContributionDetailResponseVO> detail(@PathVariable Long contributionId) {
        CommunityContributionDetailResponseVO contributionDetail = contributionService.getDetail(contributionId);
        return PAIResponseBeanUtil.success(contributionDetail);
    }

    /**
     * 分页查询共建列表
     *
     * @param pageNo    页码
     * @param pageSize  页大小
     * @param submitter 提交人（可选）
     * @param assignee  处理人（可选）
     * @param type      类型（可选）
     * @param status    状态（可选）
     * @param priority  优先级（可选）
     * @param category  分类（可选）
     * @param title     标题关键词（可选）
     * @return 分页共建列表
     */
    @Override
    public PAIResponseBean<PAIPageResponseBeanUtil<List<CommunityContributionBaseResponseVO>>> list(
            @RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(value = "submitter", required = false) String submitter,
            @RequestParam(value = "assignee", required = false) String assignee,
            @RequestParam(value = "type", required = false) Integer type,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "priority", required = false) Integer priority,
            @RequestParam(value = "category", required = false) String category,
            @RequestParam(value = "title", required = false) String title) {
        
        PAIPageResponseBeanUtil<List<CommunityContributionBaseResponseVO>> result = 
                contributionService.getContributionList(pageNo, pageSize, submitter, assignee, 
                        type, status, priority, category, title);
        return PAIResponseBeanUtil.success(result);
    }

    /**
     * 查询用户提交的共建列表
     *
     * @param userId   用户ID
     * @param pageNo   页码
     * @param pageSize 页大小
     * @param status   状态（可选）
     * @return 分页共建列表
     */
    @Override
    public PAIResponseBean<PAIPageResponseBeanUtil<List<CommunityContributionBaseResponseVO>>> listBySubmitter(
            @PathVariable String userId,
            @RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(value = "status", required = false) Integer status) {
        
        PAIPageResponseBeanUtil<List<CommunityContributionBaseResponseVO>> result = 
                contributionService.getContributionList(pageNo, pageSize, userId, null, 
                        null, status, null, null, null);
        return PAIResponseBeanUtil.success(result);
    }

    /**
     * 查询处理人的共建列表
     *
     * @param userId   用户ID
     * @param pageNo   页码
     * @param pageSize 页大小
     * @param status   状态（可选）
     * @return 分页共建列表
     */
    @Override
    public PAIResponseBean<PAIPageResponseBeanUtil<List<CommunityContributionBaseResponseVO>>> listByAssignee(
            @PathVariable String userId,
            @RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(value = "status", required = false) Integer status) {
        
        PAIPageResponseBeanUtil<List<CommunityContributionBaseResponseVO>> result = 
                contributionService.getContributionList(pageNo, pageSize, null, userId, 
                        null, status, null, null, null);
        return PAIResponseBeanUtil.success(result);
    }

    /**
     * 变更共建状态
     *
     * @param statusChangeRequest 状态变更请求
     * @return 变更结果
     */
    @Override
    public PAIResponseBean<Boolean> changeStatus(@RequestBody ContributionStatusChangeRequestVO statusChangeRequest) {
        return PAIResponseBeanUtil.success(workflowService.changeStatus(statusChangeRequest));
    }

    /**
     * 分配处理人
     *
     * @param contributionId 共建ID
     * @param assignee       处理人
     * @param operator       操作人
     * @return 分配结果
     */
    @Override
    public PAIResponseBean<Boolean> assign(@PathVariable Long contributionId,
                                          @RequestParam String assignee,
                                          @RequestParam String operator) {
        return PAIResponseBeanUtil.success(workflowService.assignContribution(contributionId, assignee, operator));
    }

    /**
     * 获取统计信息
     *
     * @return 统计信息
     */
    @Override
    public PAIResponseBean<Map<String, Object>> getStatistics() {
        return PAIResponseBeanUtil.success(statisticsService.getStatistics());
    }

    /**
     * 获取用户仪表板数据
     *
     * @param userId 用户ID
     * @return 仪表板数据
     */
    @Override
    public PAIResponseBean<Map<String, Object>> getUserDashboard(@PathVariable String userId) {
        return PAIResponseBeanUtil.success(statisticsService.getUserDashboard(userId));
    }

    /**
     * 批量变更状态
     *
     * @param contributionIds 共建ID列表（逗号分隔）
     * @param newStatus       新状态
     * @param operator        操作人
     * @param reason          变更原因
     * @return 操作结果
     */
    @PostMapping("/batch/status")
    public PAIResponseBean<Map<String, Object>> batchChangeStatus(
            @RequestParam String contributionIds,
            @RequestParam Integer newStatus,
            @RequestParam String operator,
            @RequestParam(required = false) String reason) {

        String[] ids = contributionIds.split(",");
        Map<String, Object> result = new HashMap<>();
        int successCount = 0;
        int failCount = 0;

        for (String idStr : ids) {
            try {
                Long contributionId = Long.parseLong(idStr.trim());
                ContributionStatusChangeRequestVO statusChangeRequest = new ContributionStatusChangeRequestVO();
                statusChangeRequest.setContributionId(contributionId);
                statusChangeRequest.setNewStatus(newStatus);
                statusChangeRequest.setOperator(operator);
                statusChangeRequest.setReason(reason);

                Boolean success = workflowService.changeStatus(statusChangeRequest);
                if (success) {
                    successCount++;
                } else {
                    failCount++;
                }
            } catch (Exception e) {
                log.error("批量变更状态失败: contributionId={}", idStr, e);
                failCount++;
            }
        }

        result.put("successCount", successCount);
        result.put("failCount", failCount);
        result.put("totalCount", ids.length);

        return PAIResponseBeanUtil.success(result);
    }

    /**
     * 批量分配处理人
     *
     * @param contributionIds 共建ID列表（逗号分隔）
     * @param assignee        处理人
     * @param operator        操作人
     * @return 操作结果
     */
    @PostMapping("/batch/assign")
    public PAIResponseBean<Map<String, Object>> batchAssign(
            @RequestParam String contributionIds,
            @RequestParam String assignee,
            @RequestParam String operator) {

        String[] ids = contributionIds.split(",");
        Map<String, Object> result = new HashMap<>();
        int successCount = 0;
        int failCount = 0;

        for (String idStr : ids) {
            try {
                Long contributionId = Long.parseLong(idStr.trim());
                Boolean success = workflowService.assign(contributionId, assignee, operator);
                if (success) {
                    successCount++;
                } else {
                    failCount++;
                }
            } catch (Exception e) {
                log.error("批量分配处理人失败: contributionId={}", idStr, e);
                failCount++;
            }
        }

        result.put("successCount", successCount);
        result.put("failCount", failCount);
        result.put("totalCount", ids.length);

        return PAIResponseBeanUtil.success(result);
    }
}
